package zipFile;


import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFlieUtils implements Serializable {


    /**
     * 要压缩的文件路径或者文件夹路径
     * @param filePaths
     * @return
     * @throws IOException
     */
    public static File listFileInfoToZip(List<ZipFileInfo> filePaths) throws IOException {

        File zipFile = File.createTempFile("temp", ".zip");

        try (FileOutputStream fos = new FileOutputStream(zipFile);
             ZipOutputStream zipOut = new ZipOutputStream(fos)) {

            for (ZipFileInfo info : filePaths) {
                File file = info.getFile();

                try (FileInputStream fis = new FileInputStream(file)) {
                    ZipEntry zipEntry = new ZipEntry(info.getZipEntryName());
                    zipOut.putNextEntry(zipEntry);

                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = fis.read(buffer)) >= 0) {
                        zipOut.write(buffer, 0, length);
                    }
                    zipOut.closeEntry();
                }
            }
        }
        return zipFile;
    }
    /////////////////////////////////////////

    /**
     * 要压缩的文件路径或者文件夹路径
     * @param filePaths
     * @return
     * @throws IOException
     */
    public static File listFileNameToZip(List<String> filePaths) throws IOException {
        File zipFile = File.createTempFile("temp", ".zip");

        try (FileOutputStream fos = new FileOutputStream(zipFile);
             ZipOutputStream zipOut = new ZipOutputStream(fos)) {

            for (String path : filePaths) {
                File file = new File(path);
                if (file.exists()) {
                    addToZip(file, file.getName(), zipOut);
                }
            }
        }

       return zipFile;
    }

    private static void addToZip(File file, String zipPath, ZipOutputStream zipOut) throws IOException {
        if (file.isDirectory()) {
            File[] children = file.listFiles();
            if (children != null) {
                for (File child : children) {
                    addToZip(child, zipPath + "/" + child.getName(), zipOut);
                }
            }
        } else {
            try (FileInputStream fis = new FileInputStream(file)) {
                ZipEntry zipEntry = new ZipEntry(zipPath);
                zipOut.putNextEntry(zipEntry);

                byte[] buffer = new byte[1024];
                int length;
                while ((length = fis.read(buffer)) >= 0) {
                    zipOut.write(buffer, 0, length);
                }
                zipOut.closeEntry();
            }
        }
    }

}
